import React, { useState, useRef, useEffect } from 'react';
import './Alerts.less';
import { Button, Input, message } from 'antd';
import {
    CopyOutlined,
    RedoOutlined,
    LikeOutlined,
    DislikeOutlined,
    SendOutlined
} from '@ant-design/icons';
import { aiService } from '../../services/aiService';
import ReactMarkdown from 'react-markdown';

interface Message {
    role: 'user' | 'assistant';
    content: string;
}

const Alerts: React.FC = () => {
    const [messages, setMessages] = useState<Message[]>([
        {
            role: 'assistant',
            content: '你好！很高兴见到你。我是齐溪水库管理系统 😊'
        }
    ]);
    const [inputValue, setInputValue] = useState('');
    const [loading, setLoading] = useState(false);
    const messagesEndRef = useRef<HTMLDivElement>(null);

    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
    };

    useEffect(() => {
        scrollToBottom();
    }, [messages]);

    const handleSend = async () => {
        if (!inputValue.trim()) return;

        const userMessage: Message = {
            role: 'user',
            content: inputValue.trim()
        };

        setMessages(prev => [...prev, userMessage]);
        setInputValue('');
        setLoading(true);

        try {
            const response = await aiService.chat([...messages, userMessage]);
            if (response.code === 200) {
                // 调整数据结构适配 DeepSeek 响应格式
                const aiMessage = {
                    role: 'assistant',
                    content: response.data.choices[0].message.content
                };
                // 修复类型不匹配问题，确保新消息的 role 类型为 'assistant' | 'user'
                setMessages(prev => [...prev, { ...aiMessage, role: aiMessage.role as 'assistant' }]);
            } else {
                message.error(response.error || '获取AI响应失败');
            }
        } catch (error) {
            message.error('发送消息失败，请重试');
        } finally {
            setLoading(false);
        }
    };

    const handleCopy = (content: string) => {
        navigator.clipboard.writeText(content);
        message.success('复制成功');
    };

    const handleKeyPress = (e: React.KeyboardEvent) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            handleSend();
        }
    };

    return (
        <div className="deepseek-container">
            {/* 顶部导航栏 */}
            <header className="header">
                <div className="logo">智控中心</div>
                <div className="header-right">用户与助理对话</div>
            </header>

            {/* 主体内容 */}
            <div className="main-content">
                {/* 左侧边栏 */}
                <div className="sidebar">
                    <Button className="new-chat-btn" icon={<RedoOutlined />}>
                        开启新对话
                    </Button>
                    <div className="today-section">
                        <div className="date-label">今天</div>
                        <div className="chat-item active">
                            用户与助理对话
                        </div>
                    </div>
                    <div className="profile-section">
                        <Button className="download-app">
                            下载 App<span className="new-tag">NEW</span>
                        </Button>
                        <div className="profile-info">
                            <div className="avatar"></div>
                            <span>个人信息</span>
                        </div>
                    </div>
                </div>

                {/* 聊天区域 */}
                <div className="chat-area">
                    <div className="chat-messages">
                        {messages.map((msg, index) => (
                            <div key={index} className={`message ${msg.role}-message`}>
                                <div className="message-content">
                                    <div className="message-text">
                                        {msg.role === 'assistant' ? (
                                            <ReactMarkdown 
                                                children={msg.content} 
                                                components={{
                                                    strong: ({node, ...props}) => <strong style={{fontWeight: 600}} {...props} />
                                                }}
                                            />
                                        ) : (
                                            msg.content
                                        )}
                                    </div>
                                    {msg.role === 'assistant' && (
                                        <div className="message-actions">
                                            <button
                                                className="action-btn copy"
                                                title="复制"
                                                onClick={() => handleCopy(msg.content)}
                                            >
                                                <CopyOutlined />
                                            </button>
                                            <button className="action-btn regenerate" title="重新生成">
                                                <RedoOutlined />
                                            </button>
                                            <button className="action-btn like" title="点赞">
                                                <LikeOutlined />
                                            </button>
                                            <button className="action-btn dislike" title="点踩">
                                                <DislikeOutlined />
                                            </button>
                                        </div>
                                    )}
                                </div>
                            </div>
                        ))}
                        <div ref={messagesEndRef} />
                    </div>

                    {/* 输入区域 */}
                    <div className="input-area">
                        <div className="input-container">
                            <Input.TextArea
                                value={inputValue}
                                onChange={(e) => setInputValue(e.target.value)}
                                onKeyPress={handleKeyPress}
                                placeholder="给 DeepSeek 发送消息"
                                autoSize={{ minRows: 1, maxRows: 6 }}
                                className="enhanced-input"
                                disabled={loading}
                            />
                            <div className="input-actions">
                                <Button className="model-selector">深度思考 (R1)</Button>
                                <Button className="web-search">联网搜索</Button>
                                <Button
                                    type="primary"
                                    icon={<SendOutlined />}
                                    className="send-button"
                                    onClick={handleSend}
                                    loading={loading}
                                    disabled={loading || !inputValue.trim()}
                                    style={{
                                        marginLeft: 'auto',
                                        borderRadius: '6px',
                                        height: '32px',
                                        padding: '0 16px'
                                    }}
                                >
                                    发送
                                </Button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}

export default Alerts;